package com.atguigu.exam.service.impl;

import com.atguigu.exam.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@Service
@Slf4j

public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;
    @Override
    public String uploadFile(MultipartFile file) {
        try{
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(minioProperties.getEndpoint())
                        .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                        .build();

        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        } else {
            System.out.println("Bucket" + minioProperties.getBucketName() + " already exists");
        }


        String uploadFileName = file.getOriginalFilename();
        String suffix = uploadFileName.substring(uploadFileName.lastIndexOf("."));
        String prefix = UUID.randomUUID().toString().replaceAll("-", "");
        String dateFormat = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
        String newFileName = dateFormat + "/" + prefix + suffix;
        InputStream is = file.getInputStream();
        long size = file.getSize();

        PutObjectArgs putObjetArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(newFileName)
                .stream(is, size, -1)
                .build();


        minioClient.putObject(putObjetArgs);
        System.out.println("文件上传成功");
        return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + newFileName;
    }catch (Exception e) {

            System.out.println("error" + e);
        }
        return null;
    }
}
